package cn.com.template.controller.budgetcalc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.commons.Paginator;
import cn.com.commons.utils.StringUtil;
import cn.com.dal.dataobject.VerifyDO;
import cn.com.dal.dataobject.cs.CompanycostDO;
import cn.com.dal.dataobject.hr.DeptDO;
import cn.com.dal.dataobject.hr.UserDO;
import cn.com.dal.dataobject.sys.DictDO;
import cn.com.dal.dataobject.sys.VerifyConfigDO;
import cn.com.service.VerifyService;
import cn.com.service.cs.CompanycostService;
import cn.com.service.hr.DeptService;
import cn.com.service.hr.UserService;
import cn.com.service.sys.DictService;
import cn.com.service.sys.VerifyConfigService;
import cn.com.support.context.UserContext;
import cn.com.support.message.MessageResult;
import cn.com.support.utils.JacksonUtil;
import cn.com.support.utils.VerifyConfigInf;
import cn.com.template.ui.Flexigrid;
import cn.com.template.utils.FlexigridUtil;

/**
 * 
 * 公司成本控制器
 * 
 * @since 1.0 2012-2-21 下午11:03:53
 * @version $Id$
 * @author Zoe
 */
@Controller
@RequestMapping("/budgetcalc/companycost")
public class CompanycostController {
	
	@Autowired
	private DictService dictService;
	
	@Autowired
	private DeptService deptService;
	
	@Autowired
	private CompanycostService companycostService;
	
	@Autowired
	private VerifyConfigService configService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private VerifyService verifyService;
	
	@RequestMapping
	public ModelAndView forwardOutsidecost(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("budgetcalc/companycost");
		
		DeptDO deptDO = deptService.selectById(UserContext.getUser().getDeptId());
		DictDO dictDO = new DictDO();
		if(null != deptDO){
			dictDO.setModule(deptDO.getName());
		}
		List<DictDO> dictLst = dictService.selectList(dictDO);
		List<Map<String, Object>> roleIdLst =  configService.getVerifyConfigRoles(VerifyConfigInf.COMPANY_COST_VERIFY).getRoleLst();
		List<UserDO> verifyLst = new ArrayList<UserDO>();
		Map<Object, Object> params = null;
		if(null != roleIdLst){
			for(Map<String, Object> roleMap : roleIdLst){
				if(roleMap.get("level").equals(1)){
					params = new HashMap<Object, Object>();
					//有效的用户
					params.put("status", 1);
					params.put("roleId", roleMap.get("id"));
					verifyLst = userService.selectListByRole(params);
					break;
				}
			}
		}
		request.setAttribute("dictLst", dictLst);
		request.setAttribute("verifyLst", verifyLst);
		
		return mav;
	}
	
	@RequestMapping("/getCompanyCost")
	@ResponseBody
	public Flexigrid getCost(HttpServletRequest request, HttpServletResponse response){
		Flexigrid flexigrid = null;
		try {
			Paginator<CompanycostDO, List<CompanycostDO>> paginator = new Paginator<CompanycostDO, List<CompanycostDO>>();
			String projectName = request.getParameter("projectName");
			CompanycostDO companycostDO = new CompanycostDO();
			if(StringUtil.isNotBlank(projectName)){
				companycostDO.setProjectName(projectName);
			}
			companycostDO.setCreator(UserContext.getUsername());
			paginator.setCondition(companycostDO);
			// 设置分页器
			paginator.setPageSize(Integer.parseInt(request.getParameter("rp")));
			paginator.setCurrentPage(Integer.parseInt(request.getParameter("page")));
			companycostService.selectByPage(paginator);
			//PACKAGE FLEXIGRID DATA
			flexigrid = FlexigridUtil.formatFlexigridData(paginator);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flexigrid;
	}
	
	@RequestMapping(value="/addCompanyCost", method=RequestMethod.POST)
	@ResponseBody
	public MessageResult<Long> addCost(HttpServletRequest request){
		MessageResult<Long> result = null;
		CompanycostDO companycostDO = null;
		List<Map<String, Object>> roleIdLst = null;
		VerifyDO verifyDO = null;
		try {
			String jsonData = request.getParameter("data");
			String username = UserContext.getUsername();
			//防止js harmful数据入库
			jsonData = jsonData.replaceAll("\"", "\\\"");
			companycostDO = (CompanycostDO) JacksonUtil.json2Bean(jsonData, CompanycostDO.class);
			if(companycostDO.getOtherCost() == null){
				companycostDO.setOtherCost(0L);
			}
			companycostDO.setStatus((byte)VerifyDO.STATUS_CREATE);
			companycostDO.setCreator(username);
			result = companycostService.insert(companycostDO);
			//报销数据入库后
			//根据审核配置角色-用户审核关系
			//入库系统审核表
			if(result.isSucceed()){
				VerifyConfigDO configDO = configService.getVerifyConfigRoles(VerifyConfigInf.COMPANY_COST_VERIFY);
				roleIdLst = configDO.getRoleLst();
				if(null != roleIdLst){
					for(Map<String, Object> roleMap : roleIdLst){
						if(roleMap.get("level").equals(1)){
							//审核记录LEVEL:1入库
							verifyDO = new VerifyDO();
							verifyDO.setBizId(companycostDO.getId());
							verifyDO.setVerifier(companycostDO.getVerifier());
							verifyDO.setModule(VerifyConfigInf.COMPANY_COST_VERIFY);
							verifyDO.setLevel((byte)1);
							verifyDO.setStatus((byte)VerifyDO.STATUS_CREATE);
							verifyDO.setSort((byte)1);
							verifyDO.setAttribute(configDO.getRoleId());
							verifyDO.setCreator(username);
							//审核发起人为第一次创建人
							//所有级别的审核发起人都为同一人
							verifyDO.setSubmitter(username);
							verifyService.insert(verifyDO);
							break;
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	//updateCost
		@RequestMapping(value="/updateCost", method=RequestMethod.POST)
		@ResponseBody
		public MessageResult<Integer> updateCost(HttpServletRequest request){
			MessageResult<Integer> result = null;
			CompanycostDO companycostDO = null;
			VerifyDO verifyDO = null;
			try {
				String jsonData = request.getParameter("data");
				String username = UserContext.getUsername();
				//防止js harmful数据入库
				jsonData = jsonData.replaceAll("\"", "\\\"");
				companycostDO = (CompanycostDO) JacksonUtil.json2Bean(jsonData, CompanycostDO.class);
				companycostDO.setModifier(username);
				//System.out.println(branchcostDO.toString());
				result = companycostService.updateById(companycostDO);
				if(result.isSucceed()){
					//update verify
					verifyDO = new VerifyDO();
					verifyDO.setId(companycostDO.getVerifyId());
					verifyDO.setVerifier(companycostDO.getVerifier());
					verifyDO.setModifier(username);
					verifyService.updateById(verifyDO);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result;
		}
		
		@RequestMapping(value="/submitVerify", method=RequestMethod.POST)
		@ResponseBody
		public MessageResult<Integer> submitVerify(@RequestParam String id, String vid){
			MessageResult<Integer> result = null;
			VerifyDO verifyDO = null;
			try {
				verifyDO = new VerifyDO();
				verifyDO.setId(Long.valueOf(vid));
				//verifyDO.setBizId(Long.valueOf(id));
				verifyDO.setStatus((byte)VerifyDO.STATUS_DOING);
				result = verifyService.updateById(verifyDO);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result;
		}
		
		@RequestMapping(value="/delVerify", method=RequestMethod.POST)
		@ResponseBody
		public MessageResult<Long> delVerify(@RequestParam String id, String vid){
			MessageResult<Long> result = null;
			Map<Object, Object> params = null;
			try {
				Long[] ids = new Long[]{Long.valueOf(id)};
				result = companycostService.deleteById(ids);
				if(result.isSucceed()){
					//update verify
					params = new HashMap<Object, Object>();
					params.put("bizId", Long.valueOf(id));
					params.put("module", VerifyConfigInf.COMPANY_COST_VERIFY);
					List<VerifyDO> res = verifyService.selectList(params);
					ids = new Long[res.size()];
					int index = 0;
					for(VerifyDO verifyDO : res){
						ids[index] = verifyDO.getId(); 
						index ++;
					}
					verifyService.deleteById(ids);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result;
		}

	@RequestMapping(value="/cancalVerify", method=RequestMethod.POST)
	@ResponseBody
	public MessageResult<Integer> cancalVerify(@RequestParam String ids){
		MessageResult<Integer> result = null;
		Map<Object, Object> params = null;
		try {
			params = new HashMap<Object, Object>();
			String[] idArr = ids.split(",");
			for(String idStr: idArr){
				params.put("bizId", Long.valueOf(idStr));
				params.put("module", VerifyConfigInf.COMPANY_COST_VERIFY);
				List<VerifyDO> res = verifyService.selectList(params);
				for(VerifyDO verifyDO : res){
					//发请人取消审核
					//-2:审核取消
					verifyDO.setStatus((byte)VerifyDO.STATUS_REJECT);
					result = verifyService.updateById(verifyDO);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
